# -*- coding: utf-8 -*-
###############################################################################
# file    : perf_monitor.py
# author  : wangyubin
# date    : 2013-08-28
# 
# brief   : 监控嵌入式系统的性能
# history : init
###############################################################################

import os,re,commands

def dic_v_2_int(dic):
    for k,v in dic.iteritems():
        dic[k] = int(v)

    return dic


def dic_v_2_float(dic):
    for k,v in dic.iteritems():
        dic[k] = float(v)

    return dic

def memory_stat():
    mem = {}
    f = open("/proc/meminfo")
    lines = f.readlines()
    f.close()
    for line in lines:
        if len(line) < 2: continue
        name = line.split(':')[0]
        var = line.split(':')[1].split()[0]
        mem[name] = long(var)
    mem['MemUsed'] = mem['MemTotal'] - mem['MemFree'] - mem['Buffers'] - mem['Cached']
    return mem

def cpu_stat():
    cpu = []
    f = open("/proc/cpuinfo")
    lines = f.readlines()
    f.close()
    for line in lines:
        p = re.compile(r'^Processor')
        if p.match(line):
            cpu.append(line.split(':')[1].lstrip())
    return cpu

def uptime_stat():
    uptime = {}
    f = open("/proc/uptime")
    con = f.read().split()
    f.close()
    all_sec = float(con[0])
    MINUTE,HOUR,DAY = 60,3600,86400
    uptime['day'] = int(all_sec / DAY )
    uptime['hour'] = int((all_sec % DAY) / HOUR)
    uptime['minute'] = int((all_sec % HOUR) / MINUTE)
    uptime['second'] = int(all_sec % MINUTE)
    uptime['Free rate'] = float(con[1]) / float(con[0])
    return uptime

def disk_stat():
    hd={}
    disk = os.statvfs("/")
    hd['available'] = disk.f_bsize * disk.f_bavail / 1024 # KB
    hd['capacity'] = disk.f_bsize * disk.f_blocks / 1024  # KB
    hd['used'] = disk.f_bsize * disk.f_bfree / 1024       # KB
    return hd


def cpu_top(cmd, reg):
    (status, output) = commands.getstatusoutput(cmd)
    if status == 0:
        # print output
        m = re.match(reg, output)
        # print m.groupdict()
        return dic_v_2_float(m.groupdict())
    else:
        return {}


def mem_free(cmd, reg):
    (status, output) = commands.getstatusoutput(cmd)
    if status == 0:
        m = re.match(reg, output)
        return dic_v_2_int(m.groupdict())
    else:
        return {}
        

def disk_df(cmd, reg):
    (status, output) = commands.getstatusoutput(cmd)
    lst_disk = []
    dic_disk = {}
    if status == 0:
        m = re.match(reg, output)
        if m:
            lst_disk.append(m.groupdict())
        # for line in output.split('\n'):
        #     m = re.match(uliweb.settings.DISK.reg_nand, line)
        #     if m:
        #         lst_disk.append(m.groupdict())
        #         continue
            
        #     m = re.match(uliweb.settings.DISK.reg_mmcblkp0, line)
        #     if m:
        #         lst_disk.append(m.groupdict())

    # init dic_disk
    dic_disk["size"] = 0
    dic_disk["used"] = 0
    dic_disk["avail"] = 0
    dic_disk["use_rate"] = 0
    
    for dic in lst_disk:
        for k,v in dic.iteritems():
            #print k, v
            dic_disk[k] += int(v)

    if len(lst_disk) > 0:
        dic_disk["use_rate"] = dic_disk["used"]*100.0 / dic_disk["size"]
        dic_disk["use_rate"] = float("%.2f" % dic_disk["use_rate"])

    return dic_disk
                

def network_ifconfig(cmd, reg):
    (status, output) = commands.getstatusoutput(cmd)
    if status == 0:
        # print output
        m = re.match(reg, output)
        # print m.groupdict()
        return dic_v_2_int(m.groupdict())
    else:
        return { "receive": 0, "trans": 0 }

